import { createApp } from 'vue'
import { createStore } from 'vuex'
import App from './App.vue'
import router from './router'
import Layui from '@layui/layui-vue'
import '@layui/layui-vue/lib/index.css'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import api from "./api/api.js";
import { ElMessage } from "element-plus";


const store = createStore({
    state: {
        flag: localStorage.getItem('sudo') == '1'
    },
    mutations: {
        modifyTrue(state) {
            // ElMessage.success('modifyTrue调用');
            state.flag = true;
        },
        modifyFalse(state) {
            // ElMessage.success('modifyFalse调用');
            state.flag = false;
        },
    }
})

const app = createApp(App)

app.use(router)
app.use(store)


//登录拦截
router.beforeEach((to,from,next)=>{

    if (to.meta.requireAuth) {//requireAuth若为true则该路由需要判断是否登录
        if (localStorage.getItem('uid') && localStorage.getItem('password')) {
            const form = {
                'uid': localStorage.getItem('uid'),
                'password': localStorage.getItem('password')
            };
            api
                .Login(form)
                .then((res) => {
                    if (res.data[0].uid == form.uid && res.data[0].password == form.password) {//判断当前的userName数据是否存在
                        next();
                    } else {
                        ElMessage.error("请先登录");
                        next({//返回登录页面
                            path: '/Login1',
                            query: {redirect: to.fullPath}
                        });
                        return;
                    }
                })
        }
        else
        {
            ElMessage.error("请先登录");
            next({//返回登录页面
                path: '/Login1',
                query: {redirect: to.fullPath}
            });
            return;
        }
    }
    else {
        next();
    }
})

app.use(Layui)
app.use(ElementPlus)
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
}

app.mount('#app')

